import axios from 'axios'
import { store } from '@/store'
import router from '@/router'
import { storage } from '@/utils/storage'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { message } from 'ant-design-vue';
import Qs from 'qs'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_BASE_URL,
  // baseURL: '/api',
  timeout: 6000, // 请求超时时间,
  // headers: { "content-type": "application/x-www-form-urlencoded" },
  withCredentials: true, //允许跨域携带cookie
  async: true,
  crossDomain: true,
})

const CODEENUM = {
  GD_SUCCESS: 200,
  GD_ERROR: 201,
  OP_SUCCESS: 300,
  OP_ERROR: 301,
  TOKEN_ERROR: 402,
  AHTU_ERROR: 403,
}


// 节流
let messageArr = [];
let timeout = null;

// 异常拦截处理器
const errorHandler = (res) => {
  if (messageArr.indexOf(res.code) === -1) {
    messageArr.push(res.code);
  }
  if (timeout) {
    clearTimeout(timeout);
  }
  timeout = setTimeout(() => {
    messageArr.map(item => {
      if (item === CODEENUM.GD_ERROR) {
        message.error(res.msg);
      } else if (item === CODEENUM.OP_SUCCESS) {
        message.success(res.msg);
      } else if (item === CODEENUM.OP_ERROR) {
        message.error(res.msg);
      } else if (item === CODEENUM.AHTU_ERROR) {
        message.error(res.msg);
        setTimeout(() => {
          router.replace({ path: '/user/login' })
        }, 1200)
      } else if (item === CODEENUM.TOKEN_ERROR) {
        message.error('没有查询到登录信息，请重新登录！');
        setTimeout(() => {
          router.replace({ path: '/user/login' })
        }, 1200)
      }
    });
    messageArr = []
  }, 500);
  return Promise.resolve(res)
}

// request interceptor
request.interceptors.request.use(config => {
  const token = store.state.app.token
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['token'] = token
  }
  config.data = Qs.stringify(config.data)
  return config
}, (err) => {
  console.error(err);
})

// response interceptor
request.interceptors.response.use((response) => {
  errorHandler(response.data)
  return response.data
}, (err) => {
  console.error(err);
})

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request
}
